package com.ruoyi.web.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.hutool.core.io.FileUtil;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.bean.ocr.WxOcrIdCardResult;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import net.dreamlu.mica.core.result.R;
import net.dreamlu.mica.core.utils.Base64Util;
import net.dreamlu.mica.core.utils.UrlUtil;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.util.Map;

/**
 * @author dyun
 */
@AllArgsConstructor
@RestController
@RequestMapping("/wx/public/support")
public class WxSupportController {
    private final WxMpService wxService;

    private final WxMaService wxMaService;

    /**
     * jsapi_ticket: https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html#62
     *
     * @param request request
     * @return jsapi_ticket
     */
    @PostMapping("/jsapi")
    public R getWxConfig(@RequestBody Map<String, Object> body) {
        // wx.config调用凭证,每日实时调用量/上限(次): 0/1000000
        WxJsapiSignature wxJsapiSignature = null;

        try {
            /*
                在执行 createJsapiSignature 产生签名时已经调用了 mpService.getJsapiTicket 同时已经调用了 mpService.getAccessToken。
                当mpService发起二者调用时先判断 isXXXExpired 判断是否过期:当发生过期时才去刷新，然后重新执行请求，而不是全局定时请求。
             */
            if (body.get("url") != null) {
                wxJsapiSignature = wxService.createJsapiSignature(body.get("url").toString());
            }
        } catch (Exception e) {
            return R.fail("获取失败");
        }

        return R.success(wxJsapiSignature);
    }

    /**
     * 身份证识别：
     * 需购买（有每天100次的免费包）：https://fuwu.weixin.qq.com/service/detail/000ce4cec24ca026d37900ed551415
     * 文档：https://developers.weixin.qq.com/doc/offiaccount/Intelligent_Interface/OCR.html
     */
    @GetMapping("ocridcard")
    public R ocrIdCard(String url) {
        WxOcrIdCardResult wxOcrIdCardResult;
        try {
            wxOcrIdCardResult = wxService.getOcrService().idCard(url);
        } catch (WxErrorException e) {
            return R.fail("身份证识别失败");
        }
        return R.success(wxOcrIdCardResult);
    }

    /**
     * TODO 未测试：小程序分享二维码：
     * https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.getUnlimited.html
     */
    @GetMapping("/qrcode")
    public R getMaShare(String scene, String page) {
        File wxaCodeUnlimit;
        try {
            wxaCodeUnlimit = wxMaService.getQrcodeService().createWxaCodeUnlimit(UrlUtil.encode(scene), page);
        } catch (WxErrorException e) {
            return R.fail("生成分享码失败");
        }
        FastByteArrayOutputStream outputStream = new FastByteArrayOutputStream();
        FileUtil.writeToStream(wxaCodeUnlimit, outputStream);
        String imgStr = "data:image/jpeg;base64," + Base64Util.encodeToString(outputStream.toByteArray());
        return R.success(imgStr);
    }

    /**
     * 小程序内容安全：
     * 文档：https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/sec-check/security.imgSecCheck.html
     */
    @GetMapping("imgcheck")
    public R imgSecCheck(String url) {
        boolean b;
        try {
            // 图片检测大小限制1M
            b = wxMaService.getSecCheckService().checkImage(url);
        } catch (WxErrorException e) {
            return R.fail("图片检测失败，请限制大小为1M");
        }
        return R.status(b, "图片内容不合格，请更换");
    }
}
